Ext.namespace('SLM');

SLM.DwcAdd = function(config) {

	var selectedTpl = new Ext.XTemplate(
			'<h3>{name}</h3>'
		, 'Source: {source_database}'
	);
	
	var resultTpl = new Ext.XTemplate(
			'<tpl for="."><div class="search-item">',
					'<h3>{name}</h3>{source_database}',
			'</div></tpl>'
	);
	
	this.cbCol = new Ext.form.ComboBox({
			store: new Ext.data.JsonStore({
					url: Config.baseUrl + 'resources/api/app.php'
				,	baseParams: {
						cmd: 'col-getlist'
					}
				,	root: 'records'
				,	id: 'id'
				, 	fields: [
							{name: 'name'}
						,	{name: 'rank'}
						,	{name: 'source_database'}
						,	{name: 'id'}
					]
			})
		,	displayField: 'name'
		,	typeAhead: false
		,	loadingText: 'Searching Catalog of Life 2008...'
		,	width: 250
		,	pageSize: 500
		,	hideTrigger: true
		,	queryParam: 'name'
		,	tpl: resultTpl
		,	minChars: 2
		,	itemSelector: 'div.search-item'			
		,	ownerCt: this
		,	listeners: {
				select: function( cb, record, i ) {
					selectedTpl.overwrite("col-info", record.data );
					Ext.get("col-info").show();
					this.ownerCt.specimen = record.data;
					this.ownerCt.btnAdd.enable();
				}
			}
	});

	this.btnAdd = new Ext.Button({
			text: 'Add Species'
		,	scope: this
		,	handler: this.addSpecies
		,	disabled: true
	});
	
	Ext.apply(this, config, {
			title: 'Add Species'
		,	iconCls: 'icon_collections'
		,	width: 300
		,	height: 250
		,	modal: true
		,	onEsc: Ext.emptyFn
		,	autoScroll: true
		,	bodyStyle: 'padding: 10px'
		,	html: 'To add a species type in the genus and all or part of the species name.<br/><br/><div>Search Catalog of Life: <div id="cb-col-search"></div><br/>Results:<div id="col-info"></div>'
		,	listeners: {
				show: function() {
					this.cbCol.render("cb-col-search");
				}
			}
		,	buttons: [ this.btnAdd, {
					text: 'Close'
				,	handler: function(){
						this.ownerCt.close();
					}
			}]
	});

	SLM.DwcAdd.superclass.constructor.apply(this, arguments);

};

Ext.extend( SLM.DwcAdd, Ext.Window, {				 
		addSpecies: function() {
			Ext.Ajax.request({
					url: Config.baseUrl + 'resources/api/app.php'
				,	scope: this
				,	success: function( response, request ) {

						var r = Ext.decode( response.responseText );
						if (r.success) {
							this.btnAdd.disable();
							this.cbCol.reset();
							this.cbCol.focus();
							Ext.get('col-info').update('<div class="col-success">Species Successfully added to Property</div>').pause(2).fadeOut();
						}
						
					}
				,	params: { 
							cmd: 'dwc-update'
						,	col_id: this.specimen.id
						,	land_id: 1
					}
			});

		}	
});